<template>
  <a-drawer
    :title="formInfo.id == undefined ? '新增' : '修改'"
    :maskClosable="true"
    width="80%"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :destroyOnClose="true"
    :visible="visible"
    style="height: calc(100% - 55px); overflow: auto; padding-bottom: 53px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :label-col="$global.labelCol"
        :wrapper-col="$global.wrapperCol"
      >
        <a-tabs
          v-model="activeTab"
          :tabBarStyle="{ borderBottom: 'solid 1px #d7d7d7' }"
        >
          <a-tab-pane key="0" tab="计划信息"></a-tab-pane>
          <a-tab-pane v-if="!isAdd" key="1" tab="设备信息"></a-tab-pane>
          <a-tab-pane v-if="!isAdd" key="2" tab="巡检信息"></a-tab-pane>
        </a-tabs>

        <div v-if="activeTab === '0'">
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                label="计划名称"
                prop="inspectionName"
                :rules="$valid.required"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-input
                  v-model="formInfo.inspectionName"
                  placeholder="请输入计划名称"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                label="巡检模板"
                prop="inspectionTemplateId"
                :rules="$valid.required"
                :maxLength="50"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-select
                  :showArrow="true"
                  :allowClear="true"
                  v-model="formInfo.inspectionTemplateId"
                  placeholder="请选择巡检模板"
                  show-search
                  @change="
                    inspectionTemplateIdChange(formInfo.inspectionTemplateId)
                  "
                >
                  <a-select-option
                    v-for="item in qualityControlTemplateList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.templateName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item
                label="巡检周期"
                prop="inspectionCycle"
                :rules="$valid.required"
                :maxLength="50"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-select
                  :showArrow="true"
                  :allowClear="true"
                  v-model="formInfo.inspectionCycle"
                  placeholder="请选择巡检周期"
                  show-search
                >
                  <a-select-option
                    v-for="item in this.$sysDictOptions('inspectionCycle')"
                    :key="item.k"
                    :value="item.k"
                  >
                    {{ item.v }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-model-item
                label="巡检类型"
                prop="inspectionType"
                :rules="$valid.required"
                :maxLength="50"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-select
                  :showArrow="true"
                  :allowClear="true"
                  v-model="formInfo.inspectionType"
                  placeholder="请选择巡检类型"
                  show-search
                >
                  <a-select-option
                    v-for="item in this.$sysDictOptions('inspectionType')"
                    :key="item.k"
                    :value="item.k"
                  >
                    {{ item.v }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item
                label="巡检人员"
                prop="inspectionPersonnel"
                :rules="$valid.required"
                :maxLength="50"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }"
              >
                <a-select
                  :size="'default'"
                  style="min-width: 200px"
                  :showArrow="true"
                  v-model="formInfo.inspectionPersonnel"
                  placeholder="请选择巡检人员"
                >
                  <a-select-option
                    v-for="item in createByList"
                    :key="item.companyId"
                    :value="item.companyId"
                  >
                    {{ item.companyName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-divider orientation="left">巡检项目明细 </a-divider>
          <a-table
            :columns="qualityControlTemplateProjectColumns"
            :dataSource="qualityControlTemplateProjectList"
            :pagination="false"
            bordered
            size="middle"
            rowKey="key"
          >
            <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
            <template
              v-for="col in editableQualityControlTemplateProjectColumns"
              :slot="col.dataIndex"
              slot-scope="text, record, index"
            >
              <div :key="col.dataIndex" class="editable-cell">
                {{ text }}
              </div>
            </template>

            <!-- 表头添加必填标识 -->
            <template slot="accessoryNameTitle" slot-scope="title">
              <span class="required-label">*</span>{{ title }}
            </template>
          </a-table>
        </div>
        <div v-if="activeTab === '1'">
          <div class="table-operator">
            <a-button
              :disabled="this.selectedRowKeys.length <= 0"
              @click="handleDelete()"
              type="default"
              v-wx-role="120101"
              >移出所选</a-button
            >
            <a-button
              @click="archiveEquipmentOpen"
              type="primary"
              icon="plus"
              v-wx-role="120101"
              >添加设备</a-button
            >
          </div>
          <a-table
            :columns="columns"
            :dataSource="loadData"
            :pagination="false"
            :scroll="{ x: 500 }"
            bordered
            size="middle"
            :row-selection="rowSelection"
            :rowKey="(record) => record.id"
          >
            <!-- 操作列 - 添加/删除行按钮 -->
            <template slot="action" slot-scope="text, record, index">
              <div class="action-buttons">
                <a @click="handleDelete(record.id)" v-wx-role="12010602">
                  移出</a
                >
              </div>
            </template>
          </a-table>
        </div>
      </a-form-model>
    </a-spin>
    <!-- class="drawer-bootom-button" -->
    <div
      v-if="activeTab === '0'"
      style="display: flex; margin-top: 10%; justify-content: flex-end"
    >
      <a-button @click="handleCancel" style="margin-right: 0.8rem"
        >取消</a-button
      >
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading"
        >保存</a-button
      >
    </div>

    <a-drawer
      :maskClosable="true"
      width="70%"
      placement="right"
      :closable="true"
      @close="archiveEquipmentClose"
      :destroyOnClose="true"
      :visible="archiveEquipmentVisible"
      style="height: calc(100% - 55px); overflow: auto; padding-bottom: 53px"
    >
      <dev-archive-equipment-list
        @ok="archiveEquipmentOk"
        @close="archiveEquipmentClose"
        ref="archiveEquipmentRef"
      ></dev-archive-equipment-list>
    </a-drawer>
  </a-drawer>
</template>

<script>
import { getAction, postAction, deleteAction } from '@/api/manage'
//import DevArchiveEquipmentList from '../DevArchiveEquipmentList.vue'
import DevArchiveEquipmentList from '../../devQuality/DevArchiveEquipmentList.vue'
import { STable, Ellipsis } from '@/components'
import { getDepartTree } from '@/api/api'
import { getCompanyList } from '@/api/api'
export default {
  name: 'DevInspectionPlanEdit',
  components: { STable, Ellipsis, DevArchiveEquipmentList },
  data() {
    return {
      archiveEquipmentVisible: false,
      isEdit: false,
      activeTab: '0',
      visible: false,
      confirmLoading: false,
      isAdd: false,
      formInfo: {
        createTime: undefined,
        qualityControlType: '0',
        templateName: undefined,
        wx: '',
      },
      createByList: [],
      url: {
        saveInfo: '/system/devInspectionPlan/save',
        getInfo: '/system/devInspectionPlan/info',
        saveApplicableEquipmentInfo:
          '/system/devInspectionPlanApplicableEquipment/save',
        getApplicableEquipmentInfo:
          '/system/devInspectionPlanApplicableEquipment/info',
        deleteApplicableEquipmentInfo:
          '/system/devInspectionPlanApplicableEquipment/delete',
        listApplicableEquipmentPage:
          '/system/devInspectionPlanApplicableEquipment/list',
        getQualityControlTemplateList:
          '/system/devQualityControlTemplate/getList',
        getByQualityControlTemplateIdList:
          '/system/devQualityControlTemplateProject/getByQualityControlTemplateIdList',
      },

      qualityControlTemplateProjectColumns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: 300,
          scopedSlots: {
            customRender: 'projectName',
            title: 'projectNameTitle',
          },
        },
        {
          title: '参考值',
          dataIndex: 'referenceValue',
          scopedSlots: {
            customRender: 'referenceValue',
          },
        },
        {
          title: '默认值',
          dataIndex: 'defaultValue',
          scopedSlots: { customRender: 'defaultValue' },
        },
      ],

      selectedRowKeys: [],

      columns: [
        {
          title: '设备短码',
          dataIndex: 'deviceShortCode',
          width: 150,
        },
        {
          title: '设备名称',
          dataIndex: 'deviceName',
          width: 150,
        },
        {
          title: '品牌',
          dataIndex: 'bind',
          width: 150,
        },
        {
          title: '型号',
          dataIndex: 'model',
          width: 150,
        },
        {
          title: '使用科室',
          dataIndex: 'usingDepartmentId',
          width: 200,
          customRender: (text) => this.getUsingDepartmentId(text),
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      departmentTree: [],
      qualityControlTemplateList: [],
      qualityControlTemplateProjectList: [],
    }
  },
  created() {
    this.getDepartment()
  },
  computed: {
    rowSelection() {
      return {
        // 选择类型：checkbox或者radio，默认是checkbox
        type: 'checkbox',
        // 选中的行键值，即每一行的key（这里我们使用id）
        selectedRowKeys: this.selectedRowKeys,
        // 选中项发生变化时的回调
        onChange: (selectedRowKeys, selectedRows) => {
          console.log('selectedRowKeys: ', selectedRowKeys)
          console.log('selectedRows: ', selectedRows)
          this.selectedRowKeys = selectedRowKeys
        },
        // 单独选中的行变化
        onSelect: (record, selected, selectedRows) => {
          console.log(record, selected, selectedRows)
        },
        // 全选变化
        onSelectAll: (selected, selectedRows, changeRows) => {
          console.log(selected, selectedRows, changeRows)
        },
      }
    },

    //开启选择
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },

    editableApplicableEquipmentColumns() {
      return this.applicableEquipmentColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasApplicableEquipmentErrors() {
      return this.applicableEquipmentList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableQualityControlTemplateProjectColumns() {
      return this.qualityControlTemplateProjectColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
  },
  methods: {
    inspectionTemplateIdChange(inspectionTemplateId) {
      this.qualityControlTemplateProjectList = []
      if (inspectionTemplateId) {
        getAction(this.url.getByQualityControlTemplateIdList, {
          qualityControlTemplateId: inspectionTemplateId,
        }).then((res) => {
          this.qualityControlTemplateProjectList = res.result.data
        })
      }
    },
    getUserList() {
      // 加载数据方法 必须为 Promise 对象
      var parameter = { pageNo: 1, pageSize: 1000000 }
      getCompanyList(Object.assign(parameter, this.queryParam)).then((res) => {
        this.createByList = res.result.data.records
        console.log('createByList>>', res.result.data.records)
      })
    },
    //使用科室
    getDepartment() {
      getDepartTree().then((res) => {
        this.departmentTree = res.result.data
      })
    },
    getUsingDepartmentId(text) {
      if (text) {
        var names = ''
        var usingDepartmentList = text.split(',')
        usingDepartmentList.forEach((usingDepartmentId) => {
          var value = this.getFindNodeByKey(
            this.departmentTree,
            usingDepartmentId
          )
          names = names + value.title + ','
        })
        if (names) {
          names = names.substring(0, names.length - 1)
        }
        console.log('value>>', names)
        return names
      }
    },
    getFindNodeByKey(tree, key) {
      console.log('XXXKey>', key)
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].value === key) {
          return tree[i] // 找到匹配项，返回该节点
        } else if (tree[i].children) {
          // 递归搜索子节点
          const found = this.getFindNodeByKey(tree[i].children, key)
          if (found) return found // 如果在子节点中找到，返回该节点
        }
      }
      return null // 未找到匹配项
    },

    archiveEquipmentOpen() {
      this.archiveEquipmentVisible = true
    },

    archiveEquipmentOk(val) {
      this.archiveEquipmentVisible = false

      var dataList = {
        inspectionId: this.formInfo.id,
        archiveEquipmentList: JSON.stringify(val),
      }
      postAction(this.url.saveApplicableEquipmentInfo, dataList).then((res) => {
        this.$message.success('设备保存成功')
        //查询设备信息
        this.getApplicableEquipmentList(this.formInfo.id)
      })
    },
    //查询设备信息
    getApplicableEquipmentList(inspectionId) {
      getAction(this.url.getApplicableEquipmentInfo, {
        inspectionId: inspectionId,
      }).then((res) => {
        this.loadData = res.result.data
      })
    },

    archiveEquipmentClose() {
      this.archiveEquipmentVisible = false
    },

    handleEdit() {
      this.isEdit = true
    },

    add() {
      this.isEdit = true
      this.isAdd = true
      this.edit()
    },
    edit(record) {
      this.$objToOverride(this.formInfo, record)

      //巡检模板列表
      getAction(this.url.getQualityControlTemplateList, {
        qualityTemplateType: '0',
      }).then((res) => {
        this.qualityControlTemplateList = res.result.data
      })
      this.getUserList()

      if (this.formInfo.id) {
        this.activeTab = record.activeTab
        this.isEdit = false
        this.isAdd = false
        getAction(this.url.getInfo, { id: record.id }).then((res) => {
          this.$nextTick(() => {
            this.formInfo = res.result.data
            this.inspectionTemplateIdChange(this.formInfo.inspectionTemplateId)
          })
        })
        //查询设备信息
        this.getApplicableEquipmentList(record.id)
      }
      this.activeTab = '0'
      this.visible = true
    },
    // 确定
    handleSubmit() {
      // 触发表单验证
      this.confirmLoading = true
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          postAction(this.url.saveInfo, this.formInfo)
            .then((res) => {
              this.$message.success(res.content)
              this.$emit('ok', this.formInfo)
              this.close()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 删除设备
    handleDelete(id) {
      if (!id) {
        // 如果没有传入，那么批量删除
        id = this.selectedRowKeys.join(',')
      }
      console.log('XXXXX', id)
      deleteAction(this.url.deleteApplicableEquipmentInfo, {
        ids: id,
      }).then((resp) => {
        this.$message.success('移出成功!')
        this.getApplicableEquipmentList(this.formInfo.id)
      })
    },
    // 关闭
    handleCancel() {
      if (this.isEdit && this.isAdd) {
        this.close()
      } else if (this.isEdit && !this.isAdd) {
        this.isEdit = !this.isEdit
      } else {
        this.close()
      }
      console.log('this.isEdit>', this.isEdit)
      console.log('this.isAdd>', this.isAdd)
      // if (this.isEdit && !this.isAdd) {
      //   this.isEdit = !this.isEdit
      // } else {
      //   this.close()
      // }
    },
    close() {
      this.$refs.ruleForm.resetFields()
      this.$objToReset(this.formInfo)
      this.$emit('close')
      this.visible = false
    },
    editorOk(val) {
      this.formInfo.content = val
    },
  },
}
</script>
<style scoped>
.ant-input[disabled] {
  margin-top: 3px;
  background-color: #fff !important;
  border: none !important;
  color: rgba(0, 0, 0, 0.65) !important;
  cursor: not-allowed;
}
.ant-input {
  padding-left: 5px;
}

.span-line-height {
  line-height: 38px;
}
</style>
